﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

[CLSCompliant(false)]
public class CPSQuery : UserControl
{
    // Fields
    private IContainer components;
    private Label lblConjunc;
    private Label lblEndParen;
    private Label lblField;
    private Label lblOperator;
    private Label lblStartParens;
    private Label lblValue;
    private bool m_fSuppressDirty;
    private bool m_LoadingData;
//    private QueryFile m_Query;
    private ArrayList m_rgFieldsSource;
    private XmlDocument m_xmlDoc;
    private int OpenParens;
    private Panel pnlQueryLabels;
    internal Panel pnlRows;
    private int Prev;
    private static List<string> ProductsList;
    private float[] PropWidths;
    private FlowLayoutPanel SepPanel;

    // Events
    public event EventHandler ColumnsChanged;

    public event EventHandler DirtyChanged;

   // public event ProductChangeEventHandler ProductChanged;

    // Methods
    public CPSQuery()
    {
        this.m_xmlDoc = new XmlDocument();
        this.PropWidths = new float[] { 0.0724f, 0.3947f, 0.1184f, 0.2632f, 0.0789f, 0.0724f };
        this.InitializeComponent();
    }

    //public CPSQuery(QueryFile psqFile)
    //{
    //    this.m_xmlDoc = new XmlDocument();
    //    this.PropWidths = new float[] { 0.0724f, 0.3947f, 0.1184f, 0.2632f, 0.0789f, 0.0724f };
    //    if (psqFile == null)
    //    {
    //        throw new ArgumentNullException("psqFile", "The query is null.");
    //    }
    //    this.InitializeComponent();
    //    this.m_Query = psqFile;
    //    this.PopulateQuery();
    //}

    //private void AddCloseParens()
    //{
    //    ((CPSQueryRow) this.pnlRows.Controls.get_Item((int) (this.pnlRows.Controls.get_Count() - 1))).IncParenClose = 1;
    //}

    //public void AddPathRow(string path, string PSDB)
    //{
    //    if (path == null)
    //    {
    //        throw new ArgumentNullException("The path is invalid");
    //    }
    //    if (!path.StartsWith(@"\"))
    //    {
    //        path = string.Format(@"\{0}", path);
    //    }
    //    for (int i = 1; (i < this.pnlRows.Controls.get_Count()) && !((CPSQueryRow) this.pnlRows.Controls.get_Item(i)).IsProduct; i = (int) (i + 1))
    //    {
    //        if ((((CPSQueryRow) this.pnlRows.Controls.get_Item(i)).IsValidExpression && ((CPSQueryRow) this.pnlRows.Controls.get_Item(i)).Field.Name.Equals("Path")) && ((((CPSQueryRow) this.pnlRows.Controls.get_Item(i)).PSDatabaseName != null) && (string.Compare(((CPSQueryRow) this.pnlRows.Controls.get_Item(i)).PSDatabaseName, PSDB, true) == 0)))
    //        {
    //            ((CPSQueryRow) this.pnlRows.Controls.get_Item(i)).Value = path;
    //            return;
    //        }
    //    }
    //    if (((this.pnlRows.Controls.get_Count() > 0) && (((CPSQueryRow) this.pnlRows.Controls.get_Item(0)).PSDatabaseName != null)) && (string.Compare(((CPSQueryRow) this.pnlRows.Controls.get_Item(0)).PSDatabaseName, PSDB, true) == 0))
    //    {
    //        this.InsertRow(1, null, this.CreateXmlRowNode("And", "Path", "Under", path));
    //    }
    //}

    //public CPSQueryRow AddRow()
    //{
    //    CPSQueryRow row = null;
    //    if (base.ParentForm != null)
    //    {
    //        base.ParentForm.set_Cursor(Cursors.WaitCursor);
    //    }
    //    if (((this.pnlRows.Controls.get_Count() > 0) && ((((CPSQueryRow) this.pnlRows.Controls.get_Item((int) (this.pnlRows.Controls.get_Count() - 1))).ParentRow != null) || ((CPSQueryRow) this.pnlRows.Controls.get_Item((int) (this.pnlRows.Controls.get_Count() - 1))).IsValidExpression)) && ((this.Products != null) && (this.Products.Length > 0)))
    //    {
    //        row = new CPSQueryRow(this, null, 0, null, 0, -1);
    //        row.DirtyChanged += new EventHandler(this.row_DirtyChanged);
    //        row.add_KeyDown(new KeyEventHandler(this.CPSQuery_KeyDown));
    //    }
    //    this.SetRowsTabOrder();
    //    if (base.ParentForm != null)
    //    {
    //        base.ParentForm.set_Cursor(Cursors.Default);
    //    }
    //    return row;
    //}

    //private CPSQueryRow AddRow(XmlNode Node, CPSQueryRow ParentRow)
    //{
    //    CPSQueryRow row = null;
    //    row = new CPSQueryRow(this, ParentRow, this.OpenParens, Node, 0, -1);
    //    this.OpenParens = 0;
    //    row.DirtyChanged += new EventHandler(this.row_DirtyChanged);
    //    row.add_KeyDown(new KeyEventHandler(this.CPSQuery_KeyDown));
    //    this.SetRowsTabOrder();
    //    return row;
    //}

    //private void AdjustLabelsWidth()
    //{
    //    int Left = 0x17;
    //    for (int idx = (int) (this.pnlQueryLabels.Controls.get_Count() - 1); idx >= 0; idx = (int) (idx - 1))
    //    {
    //        this.pnlQueryLabels.Controls.get_Item(idx).set_Left(Left);
    //        Left = (int) (Left + ((int) ((this.Prev - 0x17) * this.PropWidths[idx])));
    //    }
    //}

    //private void AdjustRowsWidth()
    //{
    //    for (int idx = 0; idx < this.pnlRows.Controls.get_Count(); idx = (int) (idx + 1))
    //    {
    //        this.pnlRows.Controls.get_Item(idx).set_Width(this.Prev);
    //    }
    //}

    //private void BuildQuery(XmlNode xmlQuery)
    //{
    //    XmlNode CurrentNode = null;
    //    this.pnlRows.SuspendLayout();
    //    IEnumerator Current = xmlQuery.ChildNodes.GetEnumerator();
    //    while (Current.MoveNext())
    //    {
    //        CurrentNode = (XmlNode) Current.get_Current();
    //        if (CurrentNode.get_Name().Equals("Group"))
    //        {
    //            if ((CurrentNode.FirstChild.Attributes.get_Count() > 0) && CurrentNode.FirstChild.Attributes.get_ItemOf("Field").get_Value().EndsWith("(+)"))
    //            {
    //                this.BuildSubObjectQuery(CurrentNode, null);
    //            }
    //            else
    //            {
    //                this.OpenParens = (int) (this.OpenParens + 1);
    //                this.BuildQuery(CurrentNode);
    //                this.AddCloseParens();
    //            }
    //        }
    //        else
    //        {
    //            this.AddRow(CurrentNode, null);
    //        }
    //    }
    //    this.pnlRows.ResumeLayout(false);
    //    this.pnlRows.PerformLayout();
    //}

    //private void BuildSubObjectQuery(XmlNode xmlQuery, CPSQueryRow SubObjParentRow)
    //{
    //    XmlNode CurrentNode = null;
    //    IEnumerator Current = xmlQuery.ChildNodes.GetEnumerator();
    //    while (Current.MoveNext())
    //    {
    //        CurrentNode = (XmlNode) Current.get_Current();
    //        if (CurrentNode.get_Name().Equals("Group"))
    //        {
    //            this.OpenParens = (int) (this.OpenParens + 1);
    //            this.BuildSubObjectQuery(CurrentNode, SubObjParentRow);
    //            this.AddCloseParens();
    //        }
    //        else
    //        {
    //            if (CurrentNode.Attributes.get_ItemOf("Field").get_Value().EndsWith("(+)"))
    //            {
    //                SubObjParentRow = this.AddRow(CurrentNode, null);
    //                continue;
    //            }
    //            this.AddRow(CurrentNode, SubObjParentRow);
    //        }
    //    }
    //}

    //private void ClearQuery()
    //{
    //    for (int idx = (int) (this.pnlRows.Controls.get_Count() - 1); idx >= 0; idx = (int) (idx - 1))
    //    {
    //        this.pnlRows.Controls.get_Item(idx).Dispose();
    //    }
    //    this.pnlRows.Controls.Clear();
    //}

    //private void CPSQuery_KeyDown(object sender, KeyEventArgs e)
    //{
    //    this.OnKeyDown(e);
    //}

    //private XmlNode CreateXmlRowNode(string Conjuction, string FieldName, string Operator, string Value)
    //{
    //    XmlNode Node = this.m_xmlDoc.CreateElement("Expression");
    //    XmlAttribute Attribute = this.m_xmlDoc.CreateAttribute("AttachWith");
    //    Attribute.set_Value(Conjuction);
    //    Node.Attributes.Append(Attribute);
    //    Attribute = this.m_xmlDoc.CreateAttribute("Field");
    //    Attribute.set_Value(FieldName);
    //    Node.Attributes.Append(Attribute);
    //    Attribute = this.m_xmlDoc.CreateAttribute("Operator");
    //    Attribute.set_Value(Operator);
    //    Node.Attributes.Append(Attribute);
    //    Attribute = this.m_xmlDoc.CreateAttribute("Value");
    //    Attribute.set_Value(Value);
    //    Node.Attributes.Append(Attribute);
    //    return Node;
    //}

    //private void Delete(CPSQueryRow RowToDelete)
    //{
    //    int idxDelRow = this.pnlRows.Controls.IndexOf(RowToDelete);
    //    int iHeight = RowToDelete.get_Height();
    //    CPSQueryRow PrevRow = null;
    //    if (RowToDelete.IsProduct)
    //    {
    //        PrevRow = (CPSQueryRow) this.pnlRows.Controls.get_Item((int) (idxDelRow - 1));
    //    }
    //    bool HasFocus = RowToDelete.get_Focused();
    //    this.pnlRows.Controls.Remove(RowToDelete);
    //    for (int idx = idxDelRow; idx < this.pnlRows.Controls.get_Count(); idx = (int) (idx + 1))
    //    {
    //        Control control1 = this.pnlRows.Controls.get_Item(idx);
    //        control1.set_Top((int) (control1.get_Top() - (iHeight + 1)));
    //        if (PrevRow != null)
    //        {
    //            if (((CPSQueryRow) this.pnlRows.Controls.get_Item(idx)).IsProduct)
    //            {
    //                PrevRow = null;
    //            }
    //            else
    //            {
    //                ((CPSQueryRow) this.pnlRows.Controls.get_Item(idx)).SetPSConnection(PrevRow.m_psCon);
    //            }
    //        }
    //    }
    //    if (HasFocus)
    //    {
    //        if (idxDelRow == this.pnlRows.Controls.get_Count())
    //        {
    //            this.pnlRows.Controls.get_Item((int) (this.pnlRows.Controls.get_Count() - 1)).Focus();
    //        }
    //        else
    //        {
    //            this.pnlRows.Controls.get_Item(idxDelRow).Focus();
    //        }
    //    }
    //    this.OnDirtyChange(new EventArgs());
    //    if (RowToDelete.ParentRow != null)
    //    {
    //        RowToDelete.ParentRow.Childs.Remove(RowToDelete);
    //    }
    //    RowToDelete.Dispose();
    //    this.SetRowsTabOrder();
    //}

    //internal void DeleteChilds(CPSQueryRow ParentRow)
    //{
    //    if (ParentRow == null)
    //    {
    //        throw new ArgumentNullException("The parent Row is invalid. Unable to delete the childs");
    //    }
    //    for (int idx = (int) (ParentRow.Childs.get_Count() - 1); idx >= 0; idx = (int) (idx - 1))
    //    {
    //        this.Delete((CPSQueryRow) ParentRow.Childs.get_Item(idx));
    //    }
    //}

    //internal void DeleteRow(CPSQueryRow RowToDelete)
    //{
    //    if (RowToDelete.CanDelete)
    //    {
    //        if (base.ParentForm != null)
    //        {
    //            base.ParentForm.set_Cursor(Cursors.WaitCursor);
    //        }
    //        this.DeleteChilds(RowToDelete);
    //        this.Delete(RowToDelete);
    //        if (base.ParentForm != null)
    //        {
    //            base.ParentForm.set_Cursor(Cursors.Default);
    //        }
    //    }
    //}

    //public void DisplayAddRemColsDlg()
    //{
    //    AddRemColsDlg dlg = null;
    //    dlg = new AddRemColsDlg(this);
    //    if (dlg.ShowDialog(this).Equals(DialogResult.OK))
    //    {
    //        bool fColumnsUpdated = false;
    //        if (dlg.Dirty)
    //        {
    //            this.m_Query.SetDisplayColumns(dlg.GetDisplayColumns());
    //            fColumnsUpdated = true;
    //        }
    //        if (dlg.GetSortColumns() != null)
    //        {
    //            this.m_Query.SetSortColumns(dlg.GetSortColumns());
    //            fColumnsUpdated = true;
    //        }
    //        if (fColumnsUpdated)
    //        {
    //            this.OnDirtyChange(EventArgs.Empty);
    //            this.OnColumnsChange(EventArgs.Empty);
    //        }
    //    }
    //    dlg.Dispose();
    //    dlg = null;
    //}

    //public void DisplaySortColsDlg()
    //{
    //    SortColsDlg dlg = null;
    //    dlg = new SortColsDlg(this, null);
    //    if (dlg.ShowDialog(this).Equals(DialogResult.OK) && dlg.Dirty)
    //    {
    //        this.m_Query.SetSortColumns(dlg.SortColumns);
    //        this.OnDirtyChange(EventArgs.Empty);
    //        this.OnColumnsChange(EventArgs.Empty);
    //    }
    //    dlg.Dispose();
    //    dlg = null;
    //}

    //protected override void Dispose(bool disposing)
    //{
    //    if (disposing && (this.components != null))
    //    {
    //        this.components.Dispose();
    //    }
    //    base.Dispose(disposing);
    //}

    //public DatastoreItemList[] ExecuteQuery()
    //{
    //    this.UpdateQueryFile();
    //    return this.m_Query.Execute();
    //}

    //internal ExpressionField[] GetDataBaseFields(string PSDB)
    //{
    //    if (this.m_rgFieldsSource == null)
    //    {
    //        this.m_rgFieldsSource = new ArrayList();
    //    }
    //    for (int idx = 0; idx < this.m_rgFieldsSource.get_Count(); idx = (int) (idx + 1))
    //    {
    //        if ((((DataBaseFields) this.m_rgFieldsSource.get_Item(idx)).PSDB == PSDB) && (((DataBaseFields) this.m_rgFieldsSource.get_Item(idx)).psItemType == this.QueryItems))
    //        {
    //            return ((DataBaseFields) this.m_rgFieldsSource.get_Item(idx)).Fields;
    //        }
    //    }
    //    ProductStudioClass psCon = this.GetPSConnection(PSDB);
    //    if (psCon == null)
    //    {
    //        return null;
    //    }
    //    psCon.GetFields(this.QueryItems);
    //    DataBaseFields dbf = new DataBaseFields(PSDB, this.QueryItems, psCon.GetFieldsFromDsi(this.QueryItems, true, true));
    //    this.m_rgFieldsSource.Add(dbf);
    //    return dbf.Fields;
    //}

    //public Column[] GetDisplayColumns()
    //{
    //    if (this.m_Query == null)
    //    {
    //        throw new PSControlsException("Unable to get the display columns. The internal store is null");
    //    }
    //    return this.m_Query.GetDisplayColumns();
    //}

    //internal string[] GetProductsList()
    //{
    //    string[] rgszProds = ProductStudioClass.GetRegisteredProducts();
    //    if ((ProductsList != null) && (ProductsList.get_Count() > 0))
    //    {
    //        List<string> tempList = new List<string>();
    //        tempList.AddRange(ProductsList);
    //        if (rgszProds != null)
    //        {
    //            for (int idx = 0; idx < rgszProds.Length; idx = (int) (idx + 1))
    //            {
    //                if (ProductsList.Contains(rgszProds[idx]))
    //                {
    //                    ProductsList.Remove(rgszProds[idx]);
    //                }
    //                else
    //                {
    //                    tempList.Add(rgszProds[idx]);
    //                }
    //            }
    //        }
    //        tempList.Sort();
    //        rgszProds = new string[tempList.get_Count()];
    //        tempList.CopyTo(rgszProds);
    //    }
    //    return rgszProds;
    //}

    //internal ProductStudioClass GetPSConnection(string Product)
    //{
    //    ProductStudioClass ConRet = null;
    //    if ((Product != null) && (Product.get_Length() > 0))
    //    {
    //        try
    //        {
    //            ConRet = ProductStudioClass.GetPSConnection(Product);
    //        }
    //        catch (Exception e)
    //        {
    //            MessageBox.Show(string.Format("Unable to connect to the \"{0}\" Product Studio DataBase at this time.\r\n\r\nAdditional Info:\r\n\r\nSource : {1}\r\nMessage : {2}", Product, e.get_Source(), e.get_Message()), "PSControls", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    //            ConRet = null;
    //        }
    //    }
    //    if (ConRet != null)
    //    {
    //        string[] szrgRegProds = ProductStudioClass.GetRegisteredProducts();
    //        bool RegisteredProduct = false;
    //        if (szrgRegProds != null)
    //        {
    //            for (int idx = 0; idx < szrgRegProds.Length; idx = (int) (idx + 1))
    //            {
    //                if (string.Compare(szrgRegProds[idx], ConRet.DatabaseName, true, CultureInfo.InvariantCulture) == 0)
    //                {
    //                    RegisteredProduct = true;
    //                    break;
    //                }
    //            }
    //        }
    //        if (!RegisteredProduct && ((ProductsList == null) || !ProductsList.Contains(ConRet.DatabaseName)))
    //        {
    //            if (DialogResult.Yes == MessageBox.Show(string.Format("Product \"{0}\" is not currently registered. Would you like to register it?", ConRet.DatabaseName), "PSControls", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
    //            {
    //                try
    //                {
    //                    ProductStudioClass.AddRegisteredProduct(ConRet.DatabaseName);
    //                    return ConRet;
    //                }
    //                catch (Exception e)
    //                {
    //                    MessageBox.Show(string.Format("Unable to add Product {0} to the registry.\r\n\r\nAdditional Info:\r\n\r\nSource : {1}\r\nMessage : {2}", ConRet.DatabaseName, e.get_Source(), e.get_Message()), "PSControls", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    //                    return ConRet;
    //                }
    //            }
    //            if (ProductsList == null)
    //            {
    //                ProductsList = new List<string>();
    //            }
    //            ProductsList.Add(ConRet.DatabaseName);
    //        }
    //    }
    //    return ConRet;
    //}

    //public SortBy[] GetSortColumns()
    //{
    //    if (this.m_Query == null)
    //    {
    //        throw new PSControlsException("Unable to get the sort columns. The internal store is null");
    //    }
    //    return this.m_Query.GetSortColumns();
    //}

    private void InitializeComponent()
    {
        this.pnlQueryLabels = new Panel();
        this.lblEndParen = new Label();
        this.lblValue = new Label();
        this.lblOperator = new Label();
        this.lblField = new Label();
        this.lblConjunc = new Label();
        this.lblStartParens = new Label();
        this.pnlRows = new Panel();
        this.SepPanel = new FlowLayoutPanel();
        this.pnlQueryLabels.SuspendLayout();
        base.SuspendLayout();
        this.pnlQueryLabels.set_BackColor(SystemColors.ActiveBorder);
        this.pnlQueryLabels.Controls.Add(this.lblEndParen);
        this.pnlQueryLabels.Controls.Add(this.lblValue);
        this.pnlQueryLabels.Controls.Add(this.lblOperator);
        this.pnlQueryLabels.Controls.Add(this.lblField);
        this.pnlQueryLabels.Controls.Add(this.lblConjunc);
        this.pnlQueryLabels.Controls.Add(this.lblStartParens);
        this.pnlQueryLabels.set_Dock(DockStyle.Top);
        this.pnlQueryLabels.set_Location(new Point(0, 0));
        this.pnlQueryLabels.set_Name("pnlQueryLabels");
        this.pnlQueryLabels.set_Size(new Size(0x328, 0x16));
        this.pnlQueryLabels.set_TabIndex(1);
        this.lblEndParen.set_FlatStyle(FlatStyle.System);
        this.lblEndParen.set_Font(new Font("Tahoma", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0));
        this.lblEndParen.set_Location(new Point(0x2ef, 4));
        this.lblEndParen.set_Name("lblEndParen");
        this.lblEndParen.set_Size(new Size(8, 0x10));
        this.lblEndParen.set_TabIndex(4);
        this.lblEndParen.set_Text(")");
        this.lblValue.set_FlatStyle(FlatStyle.System);
        this.lblValue.set_Font(new Font("Tahoma", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0));
        this.lblValue.set_Location(new Point(0x237, 4));
        this.lblValue.set_Name("lblValue");
        this.lblValue.set_Size(new Size(40, 0x10));
        this.lblValue.set_TabIndex(3);
        this.lblValue.set_Text("Value");
        this.lblOperator.set_FlatStyle(FlatStyle.System);
        this.lblOperator.set_Font(new Font("Tahoma", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0));
        this.lblOperator.set_Location(new Point(0x161, 4));
        this.lblOperator.set_Name("lblOperator");
        this.lblOperator.set_Size(new Size(0x3f, 0x10));
        this.lblOperator.set_TabIndex(2);
        this.lblOperator.set_Text("Operator");
        this.lblField.set_FlatStyle(FlatStyle.System);
        this.lblField.set_Font(new Font("Tahoma", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0));
        this.lblField.set_Location(new Point(0xbf, 4));
        this.lblField.set_Name("lblField");
        this.lblField.set_Size(new Size(0x3f, 0x10));
        this.lblField.set_TabIndex(1);
        this.lblField.set_Text("Field Name");
        this.lblConjunc.set_FlatStyle(FlatStyle.System);
        this.lblConjunc.set_Font(new Font("Tahoma", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0));
        this.lblConjunc.set_Location(new Point(0x55, 4));
        this.lblConjunc.set_Name("lblConjunc");
        this.lblConjunc.set_Size(new Size(0x30, 0x10));
        this.lblConjunc.set_TabIndex(5);
        this.lblConjunc.set_Text("And/Or");
        this.lblStartParens.set_FlatStyle(FlatStyle.System);
        this.lblStartParens.set_Font(new Font("Tahoma", 8.25f, FontStyle.Bold, GraphicsUnit.Point, 0));
        this.lblStartParens.set_Location(new Point(0x29, 5));
        this.lblStartParens.set_Name("lblStartParens");
        this.lblStartParens.set_Size(new Size(8, 0x10));
        this.lblStartParens.set_TabIndex(0);
        this.lblStartParens.set_Text("(");
        this.pnlRows.set_AutoScroll(true);
        this.pnlRows.set_BackColor(SystemColors.Window);
        this.pnlRows.set_Dock(DockStyle.Fill);
        this.pnlRows.set_Location(new Point(0, 0x19));
        this.pnlRows.set_Name("pnlRows");
        this.pnlRows.set_Size(new Size(0x328, 0xcf));
        this.pnlRows.set_TabIndex(2);
        this.pnlRows.add_Click(new EventHandler(this.pnlRows_Click));
        this.pnlRows.add_SizeChanged(new EventHandler(this.pnlRows_SizeChanged));
        this.SepPanel.set_Dock(DockStyle.Top);
        this.SepPanel.set_Location(new Point(0, 0x16));
        this.SepPanel.set_Name("SepPanel");
        this.SepPanel.set_Size(new Size(0x328, 3));
        this.SepPanel.set_TabIndex(3);
        this.set_AutoScroll(true);
        base.Controls.Add(this.pnlRows);
        base.Controls.Add(this.SepPanel);
        base.Controls.Add(this.pnlQueryLabels);
        this.set_Font(new Font("Tahoma", 8.25f, FontStyle.Regular, GraphicsUnit.Point, 0));
        base.set_Name("CPSQuery");
        base.set_Size(new Size(0x328, 0xe8));
        this.pnlQueryLabels.ResumeLayout(false);
        base.ResumeLayout(false);
    }

    private CPSQueryRow Insert(int RowIndex, CPSQueryRow ParentRow, XmlNode Node)
    {
        if (base.ParentForm != null)
        {
            base.ParentForm.set_Cursor(Cursors.WaitCursor);
        }
        this.pnlRows.Controls.get_Item(RowIndex).get_TabIndex();
        if (RowIndex == 0)
        {
            RowIndex = (int) (RowIndex + 1);
        }
        CPSQueryRow row = null;
        row = new CPSQueryRow(this, ParentRow, 0, Node, 0, RowIndex);
        this.SetRowsTabOrder();
        if (base.ParentForm != null)
        {
            base.ParentForm.set_Cursor(Cursors.Default);
        }
        return row;
    }

    internal void InsertRow(int RowIndex)
    {
        this.InsertRow(RowIndex, ((RowIndex > 0) && (RowIndex < this.pnlRows.Controls.get_Count())) ? ((CPSQueryRow) this.pnlRows.Controls.get_Item(RowIndex)).ParentRow : null, null);
    }

    internal CPSQueryRow InsertRow(int RowIndex, CPSQueryRow ParentRow, XmlNode Node)
    {
        if (RowIndex < 0)
        {
            throw new ArgumentOutOfRangeException("RowIndex", "The index has to be a positive value.");
        }
        if (RowIndex > (this.pnlRows.Controls.get_Count() - 1))
        {
            return this.AddRow(Node, ParentRow);
        }
        return this.Insert(RowIndex, ParentRow, Node);
    }

    public void LoadNewQuery()
    {
        this.LoadNewQuery(string.Empty);
    }

    public void LoadNewQuery(string szPSDB)
    {
        this.m_Query = new QueryFile();
        this.m_Query.New(szPSDB, QueryFile.QueryMode.Bugs);
        this.PopulateQuery();
    }

    public void LoadQuery(string path)
    {
        QueryFile tempFile = new QueryFile();
        tempFile.Load(path);
        this.m_Query = tempFile;
        this.PopulateQuery();
    }

    private void m_Query_ModeChanged(object sender, EventArgs e)
    {
        this.ClearQuery();
        if (this.m_Query.CurrentMode != QueryFile.QueryMode.Contacts)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(this.m_Query.CurrentXmlQuery);
            this.BuildQuery(xmlDoc.FirstChild);
        }
    }

    private void OnColumnsChange(EventArgs e)
    {
        if (this.onColumnsChange != null)
        {
            this.onColumnsChange(this, e);
        }
    }

    protected virtual void OnDirtyChange(EventArgs e)
    {
        if (!this.m_fSuppressDirty && (this.onDirtyChange != null))
        {
            this.onDirtyChange(this, e);
        }
    }

    private void OnProductChange(MainProductChangedEventArgs e)
    {
        if (this.onProductChange != null)
        {
            this.onProductChange(this, e);
        }
    }

    private void pnlRows_Click(object sender, EventArgs e)
    {
        this.AddRow();
    }

    private void pnlRows_SizeChanged(object sender, EventArgs e)
    {
        if ((this.Prev != this.pnlRows.ClientRectangle.get_Width()) && (this.pnlRows.ClientRectangle.get_Width() > 500))
        {
            this.Prev = this.pnlRows.ClientRectangle.get_Width();
            this.AdjustLabelsWidth();
            this.AdjustRowsWidth();
        }
    }

    private void PopulateQuery()
    {
        this.m_LoadingData = true;
        this.m_Query.ModeChanged += new EventHandler(this.m_Query_ModeChanged);
        XmlDocument xmlDoc = new XmlDocument();
        this.pnlRows.SuspendLayout();
        this.ClearQuery();
        if (((this.CurrentMode == QueryFile.QueryMode.Bugs) || (this.CurrentMode == QueryFile.QueryMode.TestCases)) || (this.CurrentMode == QueryFile.QueryMode.TestResults))
        {
            xmlDoc.LoadXml(this.m_Query.CurrentXmlQuery);
            this.BuildQuery(xmlDoc.FirstChild);
        }
        this.m_LoadingData = false;
        this.pnlRows.ResumeLayout(false);
        this.pnlRows.PerformLayout();
    }

    private void row_DirtyChanged(object sender, EventArgs e)
    {
        if (e is MainProductChangedEventArgs)
        {
            MainProductChangedEventArgs evArg = e as MainProductChangedEventArgs;
            this.m_Query.PrimaryProduct = evArg.Product;
            this.OnProductChange(evArg);
        }
        this.OnDirtyChange(e);
    }

    public void Save()
    {
        this.SaveAs(this.m_Query.CurrentPath);
    }

    public void SaveAs(string path)
    {
        if (this.m_Query.CurrentMode != QueryFile.QueryMode.Contacts)
        {
            this.m_Query.PrimaryProduct = this.Product;
            this.m_Query.CurrentXmlQuery = this.Queries;
        }
        this.m_Query.Save(path);
    }

    protected override void ScaleCore(float dx, float dy)
    {
    }

    public void SetDisplayColumns(Column[] Columns)
    {
        if (this.m_Query == null)
        {
            throw new PSControlsException("Unable to set the Display columns. The internal Query object is null.");
        }
        this.m_Query.SetDisplayColumns(Columns);
    }

    private void SetRowsTabOrder()
    {
        for (int idx = 0; idx < this.pnlRows.Controls.get_Count(); idx = (int) (idx + 1))
        {
            this.pnlRows.Controls.get_Item(idx).set_TabIndex(idx);
        }
    }

    public void SetSortColumn(string ColumnName, bool Ascending)
    {
        if (this.m_Query == null)
        {
            throw new PSControlsException("Unable to set the Sort column. The internal Query object is null.");
        }
        this.m_Query.SetSortColumn(ColumnName, Ascending);
    }

    public void SetSortColumns(SortBy[] Columns)
    {
        if (this.m_Query == null)
        {
            throw new PSControlsException("Unable to set the Sort columns. The internal Query object is null.");
        }
        this.m_Query.SetSortColumns(Columns);
    }

    public void UpdateDisplayColumnWidth(string ColumnName, int Width)
    {
        if (this.m_Query == null)
        {
            throw new PSControlsException("Unable to Update the Display column. The internal Query object is null.");
        }
        this.m_Query.SetDisplayColumnWidth(ColumnName, Width);
    }

    public void UpdateQueryFile()
    {
        this.m_Query.PrimaryProduct = this.Product;
        this.m_Query.CurrentXmlQuery = this.Queries;
    }

    // Properties
    public QueryFile.QueryMode CurrentMode
    {
        get
        {
            if (this.m_Query != null)
            {
                return this.m_Query.CurrentMode;
            }
            return QueryFile.QueryMode.None;
        }
        set
        {
            if ((this.m_Query != null) && (this.m_Query.CurrentMode != value))
            {
                if (this.CurrentMode != QueryFile.QueryMode.Contacts)
                {
                    this.m_Query.PrimaryProduct = this.Product;
                    this.m_Query.CurrentXmlQuery = this.Queries;
                }
                this.m_Query.CurrentMode = value;
            }
        }
    }

    public string CurrentPath
    {
        get
        {
            if (this.m_Query != null)
            {
                return this.m_Query.CurrentPath;
            }
            return null;
        }
    }

    public string[] Fields
    {
        get
        {
            StringCollection queryFields = new StringCollection();
            ExpressionField[] fields = null;
            foreach (CPSQueryRow queryRow in this.pnlRows.Controls)
            {
                if (queryRow.IsProduct)
                {
                    fields = this.GetDataBaseFields(queryRow.PSDatabaseName);
                    if (fields != null)
                    {
                        ExpressionField[] expressionField = fields;
                        for (int i = 0; i < expressionField.Length; i = (int) (i + 1))
                        {
                            ExpressionField field = expressionField[i];
                            if ((field.Type != FieldType.LargeText) && !queryFields.Contains(field.Name))
                            {
                                queryFields.Add(field.Name);
                            }
                        }
                    }
                }
            }
            if (queryFields.get_Count() > 0)
            {
                queryFields.Remove("Product");
                queryFields.Remove("Path");
            }
            string[] rgszRet = null;
            if (queryFields.get_Count() > 0)
            {
                rgszRet = new string[queryFields.get_Count()];
                queryFields.CopyTo(rgszRet, 0);
            }
            return rgszRet;
        }
    }

    internal bool LoadingData
    {
        get
        {
            return this.m_LoadingData;
        }
    }

    public string Product
    {
        get
        {
            if (this.m_Query != null)
            {
                return this.m_Query.PrimaryProduct;
            }
            return null;
        }
        set
        {
            if ((value != null) && ProductStudioClass.IsValidProduct(value))
            {
                if (this.pnlRows.Controls.get_Count() > 0)
                {
                    ((CPSQueryRow) this.pnlRows.Controls.get_Item(0)).Value = value;
                }
                else
                {
                    this.OnProductChange(new MainProductChangedEventArgs(value));
                }
                if (this.m_Query != null)
                {
                    this.m_Query.PrimaryProduct = value;
                }
            }
        }
    }

    public string[] Products
    {
        get
        {
            ArrayList rg = new ArrayList();
            for (int idx = 0; idx < this.pnlRows.Controls.get_Count(); idx = (int) (idx + 1))
            {
                if (((CPSQueryRow) this.pnlRows.Controls.get_Item(idx)).IsProduct && (((CPSQueryRow) this.pnlRows.Controls.get_Item(idx)).Value != string.Empty))
                {
                    rg.Add(((CPSQueryRow) this.pnlRows.Controls.get_Item(idx)).Value);
                }
            }
            if (rg.get_Count() == 0)
            {
                return null;
            }
            string[] rgszRet = new string[rg.get_Count()];
            rg.CopyTo(rgszRet);
            return rgszRet;
        }
    }

    public string Queries
    {
        get
        {
            StringWriter sw = new StringWriter();
            XmlTextWriter xmlw = new XmlTextWriter(sw);
            xmlw.set_Indentation(2);
            xmlw.WriteStartElement("QueryBuilder");
            int OpenParens = 0;
            int CloseParens = 0;
            try
            {
                for (int i = 0; i < this.pnlRows.Controls.get_Count(); i = (int) (i + 1))
                {
                    CPSQueryRow Row = this.pnlRows.Controls.get_Item(i) as CPSQueryRow;
                    if (Row != null)
                    {
                        OpenParens = (int) (OpenParens + Row.NumParenOpen);
                        for (int iPar = 0; iPar < Row.NumParenOpen; iPar = (int) (iPar + 1))
                        {
                            xmlw.WriteStartElement("Group");
                        }
                        if (Row.Field.Type == FieldType.SubObject)
                        {
                            xmlw.WriteStartElement("Group");
                            OpenParens = (int) (OpenParens + 1);
                        }
                        xmlw.WriteStartElement("Expression");
                        xmlw.WriteAttributeString("AttachWith", Row.ConjValue);
                        xmlw.WriteAttributeString("Field", Row.Field.ToString());
                        xmlw.WriteAttributeString("Operator", Row.Operator);
                        xmlw.WriteAttributeString("Value", Row.PSQValue);
                        xmlw.WriteEndElement();
                        for (int iPar = 0; iPar < Row.NumParenClose; iPar = (int) (iPar + 1))
                        {
                            xmlw.WriteEndElement();
                        }
                        CloseParens = (int) (CloseParens + Row.NumParenClose);
                        if ((Row.ParentRow != null) && (Row.ParentRow.Childs.IndexOf(Row) == (Row.ParentRow.Childs.get_Count() - 1)))
                        {
                            xmlw.WriteEndElement();
                            CloseParens = (int) (CloseParens + 1);
                        }
                    }
                }
                xmlw.WriteEndElement();
            }
            catch (InvalidOperationException e)
            {
                if (string.Compare(e.get_Message(), "There was no XML start tag open.", true) == 0)
                {
                    throw new PSControlsException("Your parenthesis are not balanced");
                }
                throw e;
            }
            if (CloseParens != OpenParens)
            {
                throw new PSControlsException("Your parenthesis are not balanced");
            }
            return sw.ToString();
        }
    }

    public PsDatastoreItemTypeEnum QueryItems
    {
        get
        {
            switch (this.CurrentMode)
            {
                case QueryFile.QueryMode.Bugs:
                    return (PsDatastoreItemTypeEnum) PsDatastoreItemTypeEnum.psDatastoreItemTypeBugs;

                case QueryFile.QueryMode.TestCases:
                    return (PsDatastoreItemTypeEnum) PsDatastoreItemTypeEnum.psDatastoreItemTypeTestCase;

                case QueryFile.QueryMode.TestResults:
                    return (PsDatastoreItemTypeEnum) PsDatastoreItemTypeEnum.psDatastoreItemTypeResult;
            }
            throw new ArgumentOutOfRangeException("Query object sypports TestCases, Test Results and Bugs. No other query modes are allowed. Please fix it");
        }
    }
}